package com.hxzy.tms.aciton;

import java.io.File;

import org.apache.commons.lang3.StringUtils;

import com.hxzy.tms.service.AttachmentService;

public class UploadAction extends AbstractAction {
    private static final long serialVersionUID = 3055720146999165964L;

    /** 通过表单域 name 属性注入 */
    private String filename;
    private File file;
    private String fileContentType;
    private String fileFileName;

    private AttachmentService attachmentService;
    private String downloadUrl;

    @Override
    public String execute() throws Exception {
        File srcFile = file;
        String downloadUrl = attachmentService.upload(fileFileName, fileContentType, srcFile);
        if (!StringUtils.EMPTY.equals(downloadUrl)) {
            this.downloadUrl = downloadUrl;
            writeJson(new ActionResult<String>(1, downloadUrl, "上传成功"));
        } else {
            addActionError("文件上传失败，请重试");
            writeJson(new ActionResult<String>(0, null, "上传失败"));
        }

        return null;
    }

    @Override
    public void validate() {
        if (getActionErrors() != null && getActionErrors().size() > 0) {
            addFieldError("filename", getActionErrors().toString());
            return;
        }
        if (StringUtils.isBlank(getFilename())) {
            addFieldError("filename", "必须输入文件名字");
        }

        if (file == null || file.length() == 0) {
            addFieldError("file", "必须上传文件");
        }

    }

    public String getFilename() {
        return filename;
    }

    public void setFilename(String filename) {
        this.filename = filename;
    }

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }

    public String getFileContentType() {
        return fileContentType;
    }

    public void setFileContentType(String fileContentType) {
        this.fileContentType = fileContentType;
    }

    public String getFileFileName() {
        return fileFileName;
    }

    public void setFileFileName(String fileFileName) {
        this.fileFileName = fileFileName;
    }

    public AttachmentService getAttachmentService() {
        return attachmentService;
    }

    public void setAttachmentService(AttachmentService attachmentService) {
        this.attachmentService = attachmentService;
    }

    public String getDownloadUrl() {
        return downloadUrl;
    }

}
